本次主題是以colab的環境進行學習的,在本篇文章中,我將講解影像辨識的基礎技能在接下來的文章中這些技能將多次出現,先讀過這些語法再繼續去看後面的文章會比較能快速上手喔。依照進度每個禮拜都會記錄不同的影像辨識方法,基本順序會從:
在我們上一篇文章中我們已經把模型準備好了,接下來我們就回到colab裡面進圖片分類吧。老樣子先把雲端硬碟掛載到colab上。
雲端硬碟掛載:
from google.colab import drive
drive.mount('/content/drive')
將雲端硬碟掛載好之後,我們先載入上次訓練的模型。
模型載入及預測:
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers
from tensorflow.keras.models import Sequential
import pathlib
import glob
import matplotlib.pyplot as plt
import numpy as np
import os
import PIL
import time
import PIL.Image as Image
import joblib
os.environ['TF_XLA_FLAGS'] = '--tf_xla_enable_xla_devices'
data_dir = pathlib.Path("/content/drive/MyDrive/train_data")
batch_size = 32
img_height = 180
img_width = 180
train_ds = tf.keras.utils.image_dataset_from_directory(
data_dir,
validation_split=0.2,
subset="training",
seed=3,
image_size=(img_height, img_width),
batch_size=batch_size)
val_ds = tf.keras.utils.image_dataset_from_directory(
data_dir,
validation_split=0.8,
subset="validation",
seed=3,
image_size=(img_height, img_width),
batch_size=batch_size)
class_names = train_ds.class_names
img_height = 180
img_width = 180
reload_model = joblib.load('/content/drive/MyDrive/model/model_1.h5')
reload_model.summary()
img = Image.open('/content/drive/MyDrive/test_data/test_image.jpg').convert('RGB')
img = img.resize((img_height, img_width))
img_array = tf.keras.utils.img_to_array(img)
img_array = tf.expand_dims(img_array, 0)
predictions = reload_model.predict(img_array)
score = tf.nn.softmax(predictions[0])
print("This image most likely belongs to {} with a {:.2f} percent confidence.".format(class_names[np.argmax(score)], 100 * np.max(score)))
實際預測結果:
test_data的資料夾共享:
https://drive.google.com/drive/folders/1p1EFvg6nQWeArdrz9tUMxNaJ-Xx81Fph?usp=sharing
如果實際預測上遇到甚麼問題或是error的話歡迎丟到留言區討論喔!
文章主題一覽:
粗體字為額外更新的文章。